package com.stylefeng.guns.order.utils;

import cn.hutool.core.io.IoUtil;
import lombok.Data;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import java.io.InputStream;

/**
 * @author dengwubo
 */
@Slf4j
@Data
@Configuration
@ConfigurationProperties(prefix = "ftp")
public class FTPUtil {

    private String hostName;
    private Integer port;
    private String userName;
    private String password;

    private FTPClient ftpClient;


    private void initFTPClient() {
        try {
            ftpClient = new FTPClient();
            ftpClient.setControlEncoding("utf-8");
            ftpClient.connect(hostName,port);
            ftpClient.login(userName, password);
            String replyString = ftpClient.getReplyString();
            log.debug(replyString);
        } catch (Exception e) {
            log.error("初始化FTP失败", e);
        }
    }

    @SneakyThrows
    public String getFileStrByAddress(String fileAddress) {
        initFTPClient();
        try (
                InputStream is = ftpClient.retrieveFileStream(fileAddress);
        ) {
            String read = IoUtil.read(is, "UTF-8");
            return read;
        } catch (Exception e) {
            log.error("获取文件信息失败",e);
            throw new Exception(e);
        }
    }

   /* public static void main(String[] args) throws Exception{
        FTPUtil ftpUtil = new FTPUtil();
        String fileStrByAddress = ftpUtil.getFileStrByAddress("seats/cgs.json");
        System.out.println(fileStrByAddress);
    }*/

}
